package org.ns.framework.datasource.redis;

import org.apache.commons.lang3.RandomStringUtils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.params.SetParams;

public class AtomicRedis implements AutoCloseable {
        public static int DEFAULT_SECONDS_TO_EXPIRE = 20;

        private Jedis jedis;
        private String masterValue;
        private Boolean master;

        private String key;

        private long secondsToExpire = DEFAULT_SECONDS_TO_EXPIRE;
        public AtomicRedis(Jedis jedis, String key, long secondsToExpire) {
            this.jedis = jedis;
            this.key = key + ".ATOMIC_REDIS";
            if (secondsToExpire > 0) {
                this.secondsToExpire = secondsToExpire;
            }
        }

        public AtomicRedis(Jedis jedis, String key) {
            this.jedis = jedis;
            this.key = key + ".ATOMIC_REDIS";
        }

        public boolean master() {
            if (this.master == null) {
                String masterValue = RandomStringUtils.random(32, "1234567890QWERTYUIOPASDFGHJKLZXCVBNM");
                String masterResult = jedis.set(key, masterValue, SetParams.setParams().nx().ex(secondsToExpire));
                this.master = masterResult != null;
                if (this.master) {
                   this.masterValue = masterValue;
                } else {
                   this.masterValue = jedis.get(key);
                }
            }
            return this.master;
        }

        @Override
        public void close()  {
            if (this.master != null) {
                if (this.master && this.masterValue != null) {
                    String masterResult = jedis.get(key);
                    if (this.masterValue.equals( masterResult)){
                        jedis.del(key);
                    }
                }
                this.master = null;
                this.masterValue = null;
            }
        }
    }